﻿var prioritizedView = false;
var FirstFilterGo = false;

var viewModel = new function () {
    // Check view is Prioritized
    var isPrioritized = $('#PrioritizedForm').val();
    if (isPrioritized != undefined && isPrioritized != null && isPrioritized == 'true') {
        prioritizedView = true;
    }

    this.LastUpdate = ko.observable(data.LastUpdateTime);

    // Configs
    this.ItemList = ko.observableArray(data.LeadWarehouseList);
    this.PageSize = ko.observable(data.PageSize);
    this.PageIndex = ko.observable(data.PageIndex);
    this.TotalPage = ko.observable(data.TotalPage);
    this.TotalRecord = ko.observable(data.TotalRecord);
    this.ColName = ko.observable("DateAdded");
    this.SortOrder = ko.observable("desc");
    this.VisibleUserColumn = ko.observable(data.IsAdmin);

    this.FieldName1 = ko.observable(data.FieldName1);
    this.FieldName2 = ko.observable(data.FieldName2);
    this.Keywords = ko.observable(data.Keywords);
    this.FieldFilter = ko.observable(data.FieldFilter);

    // Calculate condition to add class
    // Fix issue in chrome
    this.LineClass = function (index, length, status) {
        if (status != "") {
            if (index == length)
                return "line new last";
            else
                return "line new";
        }
        else {
            if (index == length)
                return "line last";
            else
                return "line";
        }
    }

    // Total Records
    this.TotalRecord = ko.observable(data.TotalRecord);
    this.PageText = ko.computed(function () {
        var total = this.TotalRecord();
        return total + " khách hàng";

    }, this);

    this.PageSizeText = ko.computed(function () {
        var pagevalue = this.PageSize().toString().replace(/\s/g, '');
        var pagesize = parseInt(pagevalue, 10);
        if (!IsNumeric(pagevalue))
            return "* Nhập một số giữa 1 - 100";
        else if (pagesize.toString() == 'NaN' || pagesize < 1 || pagesize > 100) {
            return "* Nhập một số giữa 1 - 100";
        }
        else {
            return "";
        }
    }, this);
    this.PageCurrentText = ko.computed(function () {
        var pagevalue = this.PageIndex().toString().replace(/\s/g, '');
        var pageindex = parseInt(pagevalue, 10);

        if (this.TotalRecord().length != 0) {
            if (!IsNumeric(pagevalue) || pagevalue == "" || pagevalue.toString() == 'NaN' || !IsNumeric(pagevalue) || pageindex < 1 || pageindex > this.TotalPage()) {
                return "* Nhập một số giữa 1 - " + this.TotalPage() + " ";
            }
            else {
                return "";
            }
        }
        return "";

    }, this);


    // Paginate
    this.PrevPage = function () {
        var page = parseInt(this.PageIndex());
        if (page > 1) {
            this.PageIndex(page - 1);
            $('#pagecurrent').data('lastValue', page - 1);
            LoadDataFromServer(0, 0);
        }
    }
    this.PrevButtonClass = ko.computed(function () {
        var page = parseInt(this.PageIndex());
        if (page > 1) {
            return "btn btn-prev-arrow prev-active";
        }
        else {
            return "btn btn-prev-arrow";
        }
    }, this);

    this.NextPage = function () {
        var page = parseInt(this.PageIndex());
        if (page < this.TotalPage()) {
            this.PageIndex(page + 1);
            $('#pagecurrent').data('lastValue', page + 1);
            LoadDataFromServer(0, 0);
        }
    }
    this.NextButtonClass = ko.computed(function () {
        if (this.PageIndex() >= this.TotalPage() || this.TotalPage() == 1) {
            return "btn btn-next-arrow next-disabled";
        }
        else {
            return "btn btn-next-arrow";
        }
    }, this);

    this.DisableNextButton = ko.computed(function () {
        if (IsNumeric(this.PageIndex())) {
            var pageIndex = parseInt(this.PageIndex(), 10);
            var maxPage = parseInt(this.TotalPage());

            if (pageIndex >= maxPage)
                return 1;
            else
                return 0;
        }
        return 0;
    }, this);

    // Sort by Colum/Order
    function SetOrder(event, ColName) {
        if (this.ColName() === ColName) {
            this.SwitchSortOrder();
        } else {
            this.ColName(ColName);
            this.SortOrder("asc");
        }
        SetTHClass(ColName, event);
        LoadDataFromServer(0, 0);
    }
    this.SetOrder = SetOrder; // Set to an knockout object
    function SwitchSortOrder() {
        if (this.SortOrder() === "asc") {
            this.SortOrder("desc");
        } else {
            this.SortOrder("asc");
        }
    }
    this.SwitchSortOrder = SwitchSortOrder;

    function SetTHClass(colName, event) {
        $("div.title").parent().find(".sort_wrapper").children("span").removeClass("asc");
        $("div.title").parent().find(".sort_wrapper").children("span").removeClass("desc");

        if (viewModel.SortOrder() === "asc") {
            $("#" + colName).children("span").addClass("asc");
        } else {
            $("#" + colName).children("span").addClass("desc");
        }
    }

    this.UserOption = ko.observable();
    this.UserOptions = ko.observableArray(data.UserAssignFilter == null ? [] : data.UserAssignFilter);

    // Assign view lead items to user
    this.ReassignLead = function (lead) {
        reasignOpen(lead);
    };

    this.AssignToUser = function () {
        var userId = $("#userOptionSelect").editableSelect('value');
        var leadId = $('#viewleadId').val();
        if (parseInt(userId) > 0)
            LoadDataFromServer(userId, leadId);
    };

    // Delete view lead items
    this.DeleteItem = function (lead) {
        confirmPopup(lead);
    };
    this.DeleteLead = function () {
        var leadId = $('#leadId').val();
        LoadDataFromServer(0, leadId);
    };

    this.RunSomething = function (viewModel, event) {
        LoadDataFromServer(0, 0);
    }

    this.UserList = ko.observableArray(data.UserFilter);
    this.LeadSourceList = ko.observableArray(data.LeadSource);
    this.StatusList = ko.observableArray(data.StatusFilter);
    this.RangeList = ko.observableArray(data.RangeFilter);
    this.GoButton = ko.observable(false);

    this.GoFilter = function () {
        FirstFilterGo = true;
        this.GoButton(true);

        LoadDataFromServer(0, 0);
    }

    // Load data
    function LoadDataFromServer(agentId, leadId) {
        // Page Size
        if (!viewModel.GoButton() && viewModel.ItemList().length == 0) {
            return false;
        }
        else {
            viewModel.GoButton(false);
        }

        var pageSizeValue = $('#pagesize').val().toString().replace(/\s/g, '');
        var pagesize = parseInt(pageSizeValue, 10);
        if (!IsNumeric(pageSizeValue) || pagesize.toString() == 'NaN' || pagesize < 0 || pagesize > 100) {
            return false;
        }

        // Page Index
        var pageIndexValue = $('#pagecurrent').val().toString().replace(/\s/g, '');
        var pageindex = parseInt(pageIndexValue, 10);

        if (!IsNumeric(pageIndexValue) || pageindex.toString() == 'NaN' || pageindex < 0 || (pageindex > viewModel.TotalPage() && FirstFilterGo == false)) {
            return false;
        }

        // Set pageindex = 1 if click go to filter
        // Filter options
        if (FirstFilterGo == true) {
            pageindex = 1;
        }

        var keywordValue = viewModel.Keywords();
        var fieldValue = viewModel.FieldFilter();

        // Priority option
        var priority = "";
        if (prioritizedView) {
            priority = prioritizedView;
        }

        // Assign
        var dataPost = {
            "keywords": keywordValue,
            "field": fieldValue,
            "pageIndex": pageindex,
            "pageSize": pagesize,
            "sortBy": viewModel.ColName(),
            "orderBy": viewModel.SortOrder(),
            "leadId": leadId,
            "assignId": agentId
        };

        var urlPost = "/Lead/FindFilters";

        // Reset false for diferent behavior
        FirstFilterGo = false;
        closePopup();

        // Json Get function to retrive data from server
        openProcess();

        // Ajax request
        // Build a list params
        // Call a request
        // Handle reponse
        $.ajax({
            type: "POST",
            url: urlPost,
            data: dataPost,
            dataType: "json",
            success: function (data, textStatus, jqXHR) {
                if (data.Error == undefined || data.Error == null) {
                    viewModel.PageIndex(data.PageIndex);
                    viewModel.TotalPage(data.TotalPage);
                    viewModel.PageSize(data.PageSize);
                    viewModel.TotalRecord(data.TotalRecord);
                    viewModel.ItemList(data.LeadWarehouseList == null ? [] : data.LeadWarehouseList);

                    // Refresh tooltip
                    hascounts();
                    nocounts();

                    // Stop progress bar
                    hideProcess();
                    closePopup();
                }
                else {
                    // Stop progress bar
                    hideProcess();
                    showPopupError();
                }
            },
            error: function (xhr, status, error) {
                // Stop progress bar
                hideProcess();
                showPopupError();
            }
        });

    }

    // Call object refresh data
    this.RefreshDataByPageSize = function () {
        LoadDataFromServer(0, 0);
    };
    this.RefreshDataByPageIndex = function () {
        LoadDataFromServer(0, 0);
    };
};


ko.applyBindings(viewModel, document.getElementById("main"));
// Tooltips
function nocounts() {
    $('.no-count').tooltip({
        showURL: false,
        track: true,
        fade: 150,
        top: -40,
        left: -100
    }).css('cursor', 'pointer');
    $('#tooltip').addClass('bold');
}
function hascounts() {
    $('.count-tooltip').tooltip({
        showURL: false,
        track: true,
        fade: 150,
        top: -100,
        left: -380,
        //extraClass: "count-tooltip-wrapperr",
        bodyHandler: function () {
            $('#tooltip').addClass('count-tooltip-wrapper');
            return $(this).find('.tooltip-simpletable').clone();
        }
    }).css('cursor', 'pointer');
}

// onMouseOver/ onMouseOut
$(function () {
    $("#startDate").datepicker();
    $("#endDate").datepicker();
});

function reasignOpen(lead) {
    $('#viewleadId').val(lead.LeadId);
    $('#username').text(lead.UserName);

    // Reset combobox state
    var el = $("#popup #userOptionSelect");
    if (el.length && el.editableSelect("select").length) {
        $(el.editableSelect("select").get(0)).val(lead.UserId);
        el.editableSelect("refreshState");
    }

    // Show popup
    $('#fancybox-overlay').show();
    $('#popup').showPopup({
        width: 520
    });
}

function confirmPopup(lead) {
    $('#leadId').val(lead.LeadId);
    $('#leadName').text(lead.Name);

    // Show popup
    $('#fancybox-overlay').show();
    $('#confirmDeleteLead').showPopup({
        width: 400
    });
}

function closePopup() {
    $('#popup').hide();
    $('#confirmDeleteLead').hide();
    $('#fancybox-overlay').hide();
    $(".fancybox-wrap").hide();
}

function openLead(leadId) {
    $('#viewleadId').val(leadId);
    $('#username').text($('#user-lead' + leadId).attr("rel"));
}

function openDelLead(leadId) {
    $('#leadId').val(leadId);
    $('#leadName').text($('#lead' + leadId).attr("rel"));
}

/* onload document */
$(document).ready(function () {
	$('#pagesize').removeClass('text-active');
	$('#pagecurrent').removeClass('text-active');
	$('#pagesize').data('lastValue', $('#pagesize').val());
	$('#pagecurrent').data('lastValue', $('#pagecurrent').val());

	// Key down, handle only for IE
	$('#pagesize').live('keydown', function (e) {
		var keyCode = e.keyCode || e.which;
		if (is_ie && keyCode == 13) {
			var lastValue = $('#pagesize').data('lastValue');
			var currentvalue = $('#pagesize').val().toString().replace(/\s/g, '');

			//console.log('last: ' + lastValue + ', current: ' + currentvalue);

			if (currentvalue != lastValue && lastValue != undefined) {
				var pagesize = parseInt(currentvalue, 10);

				if (!IsNumeric(currentvalue) || pagesize.toString() == 'NaN' || pagesize < 1 || pagesize > 100) {
					//viewModel.PageSizeText("* Please enter a number between 1 - 100");
				}
				else {
					$('#pagesize').data('lastValue', currentvalue);
					$('#pagecurrent').val("1");

					e.preventDefault();
					viewModel.RefreshDataByPageSize();

					return false;
				}
			}
			else {
				$('#pagesize').data('lastValue', currentvalue);
			}
		}
	});
	$('#pagecurrent').live('keydown', function (e) {
		var keyCode = e.keyCode || e.which;

		if (is_ie && keyCode == 13) {
			var lastValue = $('#pagecurrent').data('lastValue');
			var currentvalue = $('#pagecurrent').val().toString().replace(/\s/g, '');
			var pageindex = parseInt(currentvalue, 10);
			//console.log('last: ' + lastValue + ', current: ' + currentvalue);

			if (currentvalue != lastValue && lastValue != undefined) {
				if (!IsNumeric(currentvalue) || currentvalue == "" || currentvalue.toString() == 'NaN' || !IsNumeric(currentvalue) || pageindex < 1 || pageindex > viewModel.TotalPage()) {
					//$('#pagecurrent').data('lastValue', currentvalue);
				}
				else {
					$('#pagecurrent').data('lastValue', currentvalue);
					e.preventDefault();
					// call custom function here
					viewModel.RefreshDataByPageIndex();
				}
			}
			else {
				$('#pagecurrent').data('lastValue', currentvalue);
			}
		}
	});


	// Handle input tag blur
	$('#pagesize').change(function (e) {
		var lastValue = $('#pagesize').data('lastValue');
		var pagevalue = $('#pagesize').val().toString().replace(/\s/g, '');
		var pagesize = parseInt(pagevalue, 10);

		if (lastValue != pagevalue) {
			if (!IsNumeric(pagevalue) || pagesize.toString() == 'NaN' || pagesize < 1 || pagesize > 100) {
				//viewModel.PageSizeText("* Please enter a number between 1 - 100");
			}
			else {
				$('#pagesize').data('lastValue', pagevalue);
				$('#pagecurrent').val("1");
				e.preventDefault();
				viewModel.RefreshDataByPageSize();
			}
		}
		else {
			$('#pagesize').data('lastValue', pagevalue);
		}
	});
	$('#pagecurrent').change(function (e) {
		var lastValue = $('#pagecurrent').data('lastValue');
		var pagevalue = $('#pagecurrent').val().toString().replace(/\s/g, '');
		var pageindex = parseInt(pagevalue, 10);

		if (lastValue != pagevalue) {
			if (!IsNumeric(pagevalue) || pagevalue == "" || pagevalue.toString() == 'NaN' || !IsNumeric(pagevalue) || pageindex < 1 || pageindex > viewModel.TotalPage()) {
				
			}
			else {
				$('#pagecurrent').data('lastValue', pagevalue);
				e.preventDefault();
				viewModel.RefreshDataByPageIndex();
			}
		}
		else {
			$('#pagecurrent').data('lastValue', pagevalue);
		}
	});

	// Show/hide priority view messages
	var showPriorityMessage = $.cookie("showPriorityMessage");
	if (showPriorityMessage == "false") {
		$('#prioritybubble').hide();
	}
	else {
		$('#prioritybubble').show();
	}

	// mouse over/out
	$('.bubble').mouseover(function () {
		$('#prioritybubble').show();
	});
	$('.bubbleinfo').mouseover(function () {
		$('#prioritybubble').show();
	});
	$('.bubbleinfo').mouseout(function () {
		$('#prioritybubble').hide();
	});
});
function viewPriorityMessage(display) {
	$('#prioritybubble').hide();
	$.cookie("showPriorityMessage", "false", { path: '/', expires: 365 });
	return false;
}
